package servlet;

import dao.CartSql;
import pojo.Book;
import pojo.Cart;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/CartServlet")
@MultipartConfig
public class CartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        String m=request.getParameter("m");
        if(m.equals("toCart")){
            try {
                toCart(request,response);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        else if(m.equals("toQueryCart")){
            try {
                toQueryCart(request,response);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        else if(m.equals("deleteCart")){
            try {
                deleteCart(request,response);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }


    }

    protected void toCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        Cart cart = new Cart();
        cart.setCommodity_img(request.getParameter("img"));
        cart.setCommodity_name(request.getParameter("name"));
        cart.setCommodity_price(Double.parseDouble(request.getParameter("price")));
        System.out.println(cart);
        CartSql.addCart(cart);
        List<Cart> cartList = CartSql.queryCart();
        request.setAttribute("cartList",cartList);
        request.getRequestDispatcher("cart.jsp").forward(request,response);

    }

    protected void toQueryCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        List<Cart> cartList = CartSql.queryCart();
        request.setAttribute("cartList",cartList);
        request.getRequestDispatcher("cart.jsp").forward(request,response);
    }
    protected void deleteCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String id = request.getParameter("id");

        CartSql.deleteCartById(Integer.parseInt(id));
    }
}
